<template>
    <div>
        <div class="article-page article-single-page">
            <div class="wp-content-lft">
                <div class="wct-wrap">
                    <div class="works-tab">
                        <el-popover popper-class="xkj-sou-pop"
                                    placement="bottom"
                                    trigger="hover">
                                    <div class="xj-search-desc">
                                    <div class="sub-desc">推荐标准：</div>
                                    <div class="sub-d">
                                        1. 信息时效/见解独到；<br/>
                                        2. 非搬运/抄袭；<br/>
                                        3. 内容深度充足；<br/>
                                        4. 结构清晰完整
                                    </div>
                                    </div>
                            <a slot="reference" :class="{ 'active': tab == 1 }" @click="chooseTab(1)">推荐</a>
                        </el-popover>
                        <!-- <a :class="{ 'active': tab == 1 }" @click="chooseTab(1)">推荐</a> -->
                        <a :class="{ 'active': tab == 2 }" @click="chooseTab(2)">最新文章</a>
                    </div>
                    <ul class="work-datas">
                        <li class="wk-d-item" :class="{'no-data':!item.id}" v-for="(item, idx) in list" :key="idx">
                            <a :href="'/article/' + item.id" target="_blank" v-if="item.id">
                                <div class="img-box">
                                    <img loading="lazy" :srcset="item.srcsets" v-lazy="item.lazy">
                                </div>
                                <div class="u-bot">
                                    <div class="at-box">
                                        <img loading="lazy"
                                            v-aimgd="{ avatar: item.member.avatar, id: item.member.id, w: 44, name: item.member.userName }">
                                    </div>
                                    <div class="at-basic">
                                        <div class="tit">{{ item.title }}</div>
                                        <div class="other">
                                            <div class="name">{{ item.member.userName }}<img loading="lazy" class="u-m-tag"
                                                    v-for="tag in item.member.tagsList" :src="tag.image" alt=""></div>
                                            <div class="nums">
                                                <span class="v-num">{{ item.seeStr }}</span>
                                                <span class="fv-num">{{ item.collectNumStr }}</span>
                                                <span class="z-num">{{ item.praiseStr }}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </li>
                    </ul>

                    <div class="pro-bot-loading" v-if="isloading">
                        <i class="el-icon-loading"></i>
                    </div>
                </div>
            </div>
            <div class="wp-content-rt custom-scroll">
                <div class="panel-tit">热门文章</div>
                <ul class="rank-datas">
                    <li v-for="(item, index) in rankArticles" :key="index" :class="{'no-data':!item.id}">
                        <a :href="'/article/' + item.id" target="_blank" v-if="item.id">
                            <div class="img-box">
                                <img loading="lazy" :srcset="item.srcsets" v-lazy="item.lazy" @error="loadError"/>
                            </div>
                            <div class="rk-d-rft">
                                <div class="tit">{{ item.title }}</div>
                                <div class="bot-d">
                                    <div class="tags">
                                        <template v-if="item.tags">
                                            <span class="tag" v-for="(tag, idx) in item.tags.split(',')"
                                                v-if="idx < 2">{{ tag }}</span>
                                        </template>
                                    </div>
                                    <div class="view-num">{{ item.seeStr }}</div>
                                </div>
                            </div>
                        </a>
                    </li>
                    <li class="view-more"><a target="_blank" href="/?t=9">查看更多</a></li>
                </ul>
                <div class="panel-tit">热门作者</div>
                <ul class="hot-gx-data">
                    <li class="item" v-for="(item, index) in members" :class="{'no-data':!item.id}">
                        <template v-if="item.id">
                            <div class="u-box">
                                <a :href="'/user' + item.id" class="img-box">
                                    <img loading="lazy" :srcset="item.srcsets" v-lazy="item.lazy" @error="loadError"/>
                                </a>
                                <div class="basic-box">
                                    <a :href="'/user' + item.id" class="tit">
                                        {{ item.userName }}
                                        <img loading="lazy" v-for="tag in item.tagsList" :src="tag.image" alt="">
                                    </a>
                                    <div class="num-b">
                                        <span>粉丝<b>{{ item.fansStr }}</b></span>
                                        <span>人气<b>{{ item.seeStr }}</b></span>
                                    </div>
                                </div>
                            </div>
                            <a class="at-btn" :class="{ 'active': item.isSubscribe > 0 }" @click="handleFollow(item)"
                                v-if="userId">{{ item.isSubscribe > 0 ? '已关注' : '关注' }}</a>
                        </template>
                    </li>
                    <li class="view-more"><a href="/rank">查看更多</a></li>
                </ul>
            </div>
            <el-drawer :with-header="false" destroy-on-close :modal="false" append-to-body :visible.sync="showInfo"
                direction="btt">
                <articleInfo @close="onInfoClose" :id="currentId" />
            </el-drawer>
        </div>
        <UnLoginMask />
    </div>
</template>

<script>
import UnLoginMask from '@/components/UnLoginMask'
import SparkMD5 from 'spark-md5'
import api from '@/api/api'
import articleInfo from '@/components/articleinfo'
export default {
    name: 'homes',
    components: { articleInfo, UnLoginMask },
    data() {
        return {
            isloading: true,
            userId: '',
            rankArticles: [{},{},{},{},{},{},{},{}],
            members: [{},{},{},{}],
            curFullPath: '',
            currentId: '',
            showInfo: false,
            tab: 1,
            params: {
                orderByColumn: 'createTime',
                pageSize: 20,
                pageNum: 1,
                isAsc: 'desc',
                rank: '首页推荐',
                categoryId: 9
            },
            totalPage: 0,
            scrollLoaded: false,
            list: [],
        }
    },
    methods: {
        loadError(e){
            e.target.removeAttribute('srcset');
        },
        async handleFollow(item) {
            if (item.isSubscribe > 0) {
                let res = await api.cancelFollowTo(item.id);
                if (res.code == 0) {
                    item.isSubscribe = 0;
                    this.$amessage.success('已取消，有缘再见～')
                }
            }
            else {
                let res = await api.followTo(item.id);
                if (res.code == 0) {
                    this.$bhelper.addCirRecord('FOLLOW');
                    this.$store.dispatch('setLeftMenu',[])
                    item.isSubscribe = 1;
                    this.$amessage.success('关注+1，灵感不断！')
                }
            }
        },
        chooseTab(_tab) {
            $('body,html').animate({
                'scrollTop': 0
            }, 0);
            this.tab = _tab;
            this.params.rank = _tab == 1 ? '首页推荐' : '';
            this.list = [];
            this.hasMore = true;
            this.params.pageNum = 1;
            this.queryList();
        },
        onInfoClose() {
            window.history.pushState({}, 0, this.curFullPath);
            document.body.style.overflow = 'inherit';
            this.showInfo = false;
        },
        handleShowInfo(_item) {
            this.currentId = _item.id;
            window.history.pushState({}, 0, '/article/' + _item.id);
            document.body.style.overflow = 'hidden';
            this.showInfo = true;
        },
        get_avatar_url(member = { id: '', avatar: '' }, n = 1, w = 30) {
            if (!member.id || !member.avatar) return this.defaultAvatar
            let hash = SparkMD5.hash(member.avatar).slice(0, 6)
            return `https://img.gameui.net/avatar-${member.id}-${hash}@${n}x${w}.webp`
        },
        onImgError(e) {
            e.target.src = require('../assets/pro/default_uimg.svg');
        },
        handleLoadingMore() {
            this.params.pageNum++
            this.queryList()
        },
        async queryList() {
            var that = this;
            that.isloading = true;
            if(that.params.pageNum==1){
                that.list=[{},{},{},{},{}];
            }
            let result = await api.articlelist(that.params);
            if(that.params.pageNum==1){
                that.list=[];
            }
            let old = that.list;
            that.isloading = false;

            result.data.map(item=>{
                let _vtime=null;
                if(item.updateTime){
                    _vtime=item.updateTime;
                }else if(item.createTime){
                    _vtime=item.createTime;
                }else if(item.create_time){
                    _vtime=item.create_time.replace('T',' ');
                }
                _vtime=Math.abs(new Date(_vtime).getTime());
                item.lazy = {
                    src:that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@1x800.webp',
                    error: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png'),
                    loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
                }
                let srcsets=[];
                srcsets.push(that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@1x800.webp 1x');
                srcsets.push(that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@2x800.webp 2x');
                srcsets.push(that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@3x800.webp 3x');
                item.srcsets=srcsets.join(',')
            })

            that.list = [...old, ...result.data]

            that.total = result.total;
            let rsnum = this.total % this.params.pageSize;

            let totalPage = rsnum == 0 ? this.total / this.params.pageSize : parseInt(this.total / this.params.pageSize + 1);
            if (result.data && (result.data.length < that.params.pageSize || that.params.pageNum >= totalPage)) {
                that.hasMore = false
            } else {
                that.hasMore = true
            }
            this.totalPage = totalPage;
            this.scrollLoaded = true
        },
        version(time) {
            let date = new Date(time)
            return date.getTime()
        },
        docScroll() {
            let that = this;
            if (that.showInfo) return;
            let jHeight = document.documentElement.scrollHeight - document.documentElement.scrollTop - document.documentElement.clientHeight

            if (that.scrollLoaded == false) return
            if (jHeight <= 200 && that.hasMore) {
                if (!localStorage.getItem('token')) {
                    that.$parent.noLoginIsTak = false;
                    that.$parent.showLoginView = true;
                    that.isloading = false;
                    window.removeEventListener('scroll', that.docScroll);
                    return;
                }
                that.scrollLoaded = false
                that.handleLoadingMore()
            }
        }
    },
    destroyed() {
        $(document).unbind('scroll')
    },
    async mounted() {
        let that=this;
        this.userId = localStorage.getItem('userId') || '';
        this.curFullPath = this.$route.fullPath;
        let res = await api.articlelist({ pageNum: 1, pageSize: 8, orderByColumn: 'see', isAsc: 'desc', categoryId: 9 });

        res.data.map(item=>{
            let _vtime=null;
            if(item.updateTime){
                _vtime=item.updateTime;
            }else if(item.createTime){
                _vtime=item.createTime;
            }else if(item.create_time){
                _vtime=item.create_time.replace('T',' ');
            }
            _vtime=Math.abs(new Date(_vtime).getTime());
            item.lazy = {
                src:that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@1x150.webp',
                error: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png'),
                loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
            }
            let srcsets=[];
            srcsets.push(that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@1x150.webp 1x');
            srcsets.push(that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@2x150.webp 2x');
            srcsets.push(that.$imgdomainurl+'article-'+item.id+'-'+_vtime+'@3x150.webp 3x');
            item.srcsets=srcsets.join(',')
        })
        this.rankArticles = res.data;

        let data = {
            pageNum: 1,
            pageSize: 4,
            showTags: '人气最多',
            isAsc: 'desc',
            orderByColumn: 'see',
            userId: this.userId
        }
        res = await api.membersRank(data);
        res.data.map(item=>{
            let _vtime=null;
            if(item.updateTime){
                _vtime=item.updateTime;
            }else if(item.createTime){
                _vtime=item.createTime;
            }else if(item.create_time){
                _vtime=item.create_time.replace('T',' ');
            }
            _vtime=Math.abs(new Date(_vtime).getTime());
            item.lazy = {
                src:that.$imgdomainurl+'avatar-'+item.id+'-'+_vtime+'@1x60.webp',
                error: require('@/assets/pro/default_sys_img.svg'),
                loading: require('@/assets/l_error_'+(localStorage.getItem('THM-STY')?localStorage.getItem('THM-STY'):'light')+'.png')
            }
            let srcsets=[];
            srcsets.push(that.$imgdomainurl+'avatar-'+item.id+'-'+_vtime+'@1x60.webp 1x');
            srcsets.push(that.$imgdomainurl+'avatar-'+item.id+'-'+_vtime+'@2x60.webp 2x');
            srcsets.push(that.$imgdomainurl+'avatar-'+item.id+'-'+_vtime+'@3x60.webp 3x');
            item.srcsets=srcsets.join(',')
        })
        this.members = res.data;
        
        this.queryList();

        window.addEventListener('scroll', this.docScroll)
    }
}

</script>